<template>
  <div class="order-management">
    <h2>订单管理</h2>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="订单编号">
          <el-input v-model="searchForm.id" placeholder="请输入订单编号"></el-input>
        </el-form-item>
        <el-form-item label="游戏类型">
          <el-select v-model="searchForm.gameTypeId" placeholder="请选择游戏类型">
            <el-option v-for="item in gameTypeList" :key="item.id" :label="item.gameTypeName" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.orderStatus" placeholder="请选择订单状态">
            <el-option label="已发布" :value="0"></el-option>
            <el-option label="游戏中" :value="1"></el-option>
            <el-option label="审核中" :value="2"></el-option>
            <el-option label="已完成" :value="3"></el-option>
            <el-option label="售后中" :value="4"></el-option>
            <el-option label="预定" :value="5"></el-option>
            <el-option label="游戏结束" :value="6"></el-option>
            <el-option label="驳回" :value="7"></el-option>
            <!-- <el-option label="待处理" :value="8"></el-option> -->
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 订单列表 -->
    <el-card>
      <el-table :data="orders" style="width: 100%" border>
        <el-table-column prop="id" label="订单编号" width="180"></el-table-column>
        <el-table-column prop="bossNickname" label="老板" width="120"></el-table-column>
        <el-table-column prop="playmateNickname" label="陪玩师" width="120"></el-table-column>
        <el-table-column prop="gameTypeName" label="游戏类型" width="120">
          <template slot-scope="scope">
            <span @click="handleGameTypeDetail(scope.row.gameTypeId)" style="color: #409EFF; cursor: pointer;">
              {{ scope.row.gameTypeName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="orderMoney" label="金额" width="100">
          <template slot-scope="scope">{{ scope.row.orderMoney | formatMoney }}</template>
        </el-table-column>
        <el-table-column prop="orderStatusName" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)">
              {{ scope.row.orderStatusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="260">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="![0, 3].includes(scope.row.orderStatus)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div style="margin-top: 20px; text-align: center;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
    
    <!-- 订单详情对话框 -->
    <el-dialog title="订单详情" :visible.sync="dialogVisible" width="60%">
      <el-form :model="currentOrder" label-width="120px">
        <el-form-item label="订单编号：">
          <span>{{ currentOrder.id }}</span>
        </el-form-item>
        <el-form-item label="订单标题：">
          <span>{{ currentOrder.orderTitle }}</span>
        </el-form-item>
        <el-form-item label="老板：">
          <span>{{ currentOrder.bossNickname }}</span>
        </el-form-item>
        <el-form-item label="陪玩师：">
          <span>{{ currentOrder.playmateNickname }}</span>
        </el-form-item>
        <el-form-item label="游戏类型：">
          <span @click="handleGameTypeDetail(currentOrder.gameTypeId)" style="color: #409EFF; cursor: pointer;">
            {{ currentOrder.gameTypeName }}
          </span>
        </el-form-item>
        <el-form-item label="订单单位：">
          <span>{{ currentOrder.orderUnit === 0 ? '局' : '小时' }}</span>
        </el-form-item>
        <el-form-item label="订单单价：">
          <span>{{ currentOrder.orderPrice | formatMoney }}</span>
        </el-form-item>
        <el-form-item label="购买数量：">
          <span>{{ currentOrder.orderBuyNumber }}</span>
        </el-form-item>
        <el-form-item label="订单金额：">
          <span>{{ currentOrder.orderMoney | formatMoney }}</span>
        </el-form-item>
        <el-form-item label="订单状态：">
          <el-tag :type="getStatusType(currentOrder.orderStatus)">
            {{ currentOrder.orderStatusName }}
          </el-tag>
        </el-form-item>
        <el-form-item label="开始时间：">
          <span>{{ currentOrder.orderStartTime }}</span>
        </el-form-item>
        <el-form-item label="结束时间：">
          <span>{{ currentOrder.orderEndTime }}</span>
        </el-form-item>
        <el-form-item label="评分：">
          <span>{{ currentOrder.orderRating || '未评分' }}</span>
        </el-form-item>
        <el-form-item label="评价：">
          <span>{{ currentOrder.orderTextComments || '无' }}</span>
        </el-form-item>
        <el-form-item label="创建时间：">
          <span>{{ currentOrder.createTime }}</span>
        </el-form-item>
        
        <!-- 售后信息折叠面板 -->
        <el-collapse v-model="activeCollapseNames" v-if="currentOrder.afterSaleId">
          <el-collapse-item title="售后信息" name="afterSales">
            <el-form-item label="售后ID：">
              <span>{{ currentOrder.afterSaleId }}</span>
            </el-form-item>
            <el-form-item label="处理结果：">
              <span>{{ currentOrder.afterResult || '暂无处理结果' }}</span>
            </el-form-item>
            <el-form-item label="创建时间：">
              <span>{{ currentOrder.afterCreateTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间：">
              <span>{{ currentOrder.afterUpdateTime }}</span>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>
        
        <el-form-item label="订单图片：" v-if="currentOrder.imgUrls && currentOrder.imgUrls.length">
          <el-image 
            v-for="(url, index) in currentOrder.imgUrls" 
            :key="index"
            :src="url" 
            style="width: 100px; height: 100px; margin-right: 10px"
            :preview-src-list="currentOrder.imgUrls">
          </el-image>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    
    <!-- 编辑订单对话框 -->
    <el-dialog title="编辑订单" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editOrder" label-width="120px" ref="editForm">
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="editOrder.orderStatus" placeholder="请选择订单状态">
            <el-option 
              v-for="item in availableStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息：">
          <el-input type="textarea" v-model="editOrder.orderNote" :rows="4"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </span>
    </el-dialog>

    <!-- 游戏类型详情对话框 -->
    <el-dialog title="游戏类型详情" :visible.sync="gameTypeDialogVisible" width="50%">
      <el-form :model="gameTypeDetail" label-width="120px">
        <el-form-item label="游戏类型ID：">
          <span>{{ gameTypeDetail.id }}</span>
        </el-form-item>
        <el-form-item label="游戏类型名称：">
          <span>{{ gameTypeDetail.gameTypeName }}</span>
        </el-form-item>
        <el-form-item label="类型描述：">
          <span>{{ gameTypeDetail.description || '无描述' }}</span>
        </el-form-item>
        <el-form-item label="创建时间：">
          <span>{{ gameTypeDetail.createTime }}</span>
        </el-form-item>
        <el-form-item label="更新时间：">
          <span>{{ gameTypeDetail.updateTime }}</span>
        </el-form-item>
        <el-form-item label="状态：">
          <el-tag :type="gameTypeDetail.status === 1 ? 'success' : 'danger'">
            {{ gameTypeDetail.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="gameTypeDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from "@/http/adminApi";

export default {
  name: "OrderManagement",
  data() {
    return {
      // 搜索表单
      searchForm: {
        id: '',
        gameTypeId: '',
        orderStatus: ''
      },
      // 订单列表数据
      orders: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      // 游戏类型列表
      gameTypeList: [],
      // 详情对话框
      dialogVisible: false,
      currentOrder: {},
      // 编辑对话框
      editDialogVisible: false,
      editOrder: {},
      // 可选的状态选项
      availableStatusOptions: [],
      // 折叠面板控制
      activeCollapseNames: [],
      // 游戏类型详情相关
      gameTypeDialogVisible: false,
      gameTypeDetail: {}
    };
  },
  filters: {
    formatMoney(value) {
      if (!value) return '0.00';
      return Number(value).toFixed(2);
    }
  },
  created() {
    this.getGameTypeList();
    this.getOrderList();
  },
  methods: {
    // 获取游戏类型列表
    getGameTypeList() {
      adminApi.getGameTypeList({ page: 1, pageSize: 100 }).then(res => {
        if (res.code === 200) {
          this.gameTypeList = res.data.list;
        }
      });
    },
    
    // 获取游戏类型详情
    handleGameTypeDetail(gameTypeId) {
      if (!gameTypeId) return;
      
      adminApi.getGameTypeDetail({ id: gameTypeId }).then(res => {
        if (res.code === 200) {
          this.gameTypeDetail = res.data;
          this.gameTypeDialogVisible = true;
        } else {
          this.$message.error(res.msg || '获取游戏类型详情失败');
        }
      }).catch(() => {
        this.$message.error('网络错误，获取游戏类型详情失败');
      });
    },
    
    // 获取订单列表
    getOrderList() {
      const params = {
        ...this.searchForm,
        page: this.currentPage,
        pageSize: this.pageSize
      };

      adminApi.getOrderList(params).then(res => {
        if (res.code === 200) {
          this.orders = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.getOrderList();
    },
    
    // 重置搜索表单
    resetForm() {
      this.searchForm = {
        id: '',
        gameTypeId: '',
        orderStatus: ''
      };
      this.currentPage = 1;
      this.getOrderList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.getOrderList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getOrderList();
    },
    
    // 查看订单详情
    handleView(row) {
      adminApi.getOrderDetail({ id: row.id }).then(res => {
        if (res.code === 200) {
          this.currentOrder = res.data;
          this.dialogVisible = true;
        }
      });
    },
    
    // 编辑订单
    handleEdit(row) {
      this.editOrder = {
        id: row.id,
        orderStatus: row.orderStatus,
        orderNote: row.orderNote || ''
      };
      
      // 设置所有可能的状态选项
      this.availableStatusOptions = [
        { label: "已发布", value: 0 },
        { label: "预定", value: 5 },
        { label: "游戏中", value: 1 },
        { label: "游戏结束", value: 6 },
        { label: "审核中", value: 2 },
        { label: "已完成", value: 3 },
        { label: "售后中", value: 4 },
        { label: "驳回", value: 7 },
        { label: "待处理", value: 8 }
      ];
      
      this.editDialogVisible = true;
    },
    
    // 获取所有状态选项（删除原有的状态流转限制）
    getAllStatusOptions() {
      // 所有状态选项
      return [
        { label: "已发布", value: 0 },
        { label: "预定", value: 5 },
        { label: "游戏中", value: 1 },
        { label: "游戏结束", value: 6 },
        { label: "审核中", value: 2 },
        { label: "已完成", value: 3 },
        { label: "售后中", value: 4 },
        { label: "驳回", value: 7 },
        { label: "待处理", value: 8 }
      ];
    },
    
    // 提交编辑
    submitEdit() {
      adminApi.updateOrderStatus({
        id: this.editOrder.id,
        status: this.editOrder.orderStatus,
        orderNote: this.editOrder.orderNote
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('更新成功');
          this.editDialogVisible = false;
          this.getOrderList();
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    
    // 删除订单
    handleDelete(row) {
      // 检查订单状态，只允许删除"已发布(0)"和"已完成(3)"的订单
      if (![0, 3].includes(row.orderStatus)) {
        this.$message.warning('只能删除"已发布"或"已完成"状态的订单');
        return;
      }
      
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        adminApi.deleteOrder({ id: row.id }).then(res => {
          if (res.code === 200) {
            this.$message.success('删除成功!');
            this.getOrderList();
          } else {
            this.$message.error(res.msg);
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        0: 'info',       // 已发布
        1: 'primary',    // 游戏中
        2: 'processing', // 审核中
        3: 'success',    // 已完成
        4: 'warning',    // 售后中
        5: 'info',       // 预定
        6: 'processing', // 游戏结束
        7: 'danger',     // 驳回
        8: 'info'        // 待处理
      };
      return statusMap[status] || 'info';
    }
  }
};
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.order-management h2 {
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
}

.el-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}
</style>